package com.nip.irregularvebsdict.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphObject;
import com.nip.irregularvebsdict.R;
import com.nip.irregularvebsdict.items.IrregularVerbDetailsItem;
import com.nip.irregularvebsdict.utilities.constants.Constants;

public class NIPVerbDetailsActivity extends Activity {

	private TextView tvWord;
	private TextView tvMean;
	public static final String NAME_KEY = "NAME_KEY";
	public static final String IMAGE_LINK_KEY = "IMAGE_LINK_KEY";
	public static final int REQUEST_CODE = 0;
	public static final int RESULT_POST_OK_CODE = 1;
	public static final int RESULT_POST_ANOTHER_ACCOUNT = 2;

	private Session.StatusCallback callback = new Session.StatusCallback() {

		@Override
		public void call(Session session, SessionState state,
				Exception exception) {

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_irregular_verbs_details);
		initialize(savedInstanceState);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// Session.getActiveSession().onActivityResult(this, requestCode,
		// resultCode, data);
		//
		// if (requestCode == REQUEST_CODE) {
		// if (resultCode == RESULT_POST_ANOTHER_ACCOUNT) {
		// logOut();
		// logIn();
		// } else if (resultCode == RESULT_POST_OK_CODE) {
		// // post feed
		// }
		// }
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// Session.saveSession(Session.getActiveSession(), outState);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onStart() {
		// Session.getActiveSession().addCallback(callback);
		super.onStart();
	}

	@Override
	protected void onStop() {
		// Session.getActiveSession().removeCallback(callback);
		super.onStop();
	}

	private void initialize(Bundle savedInstanceState) {

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();

		if (bundle == null) {
			return;
		}
		IrregularVerbDetailsItem detailsItem = (IrregularVerbDetailsItem) bundle
				.getSerializable(Constants.IRREGULAR_VERB_DETAILS_KEY);
		if (detailsItem == null) {
			return;
		}
		tvWord = (TextView) findViewById(R.id.tvWork);
		tvMean = (TextView) findViewById(R.id.tvDetails);
		tvWord.setText("♥ " + detailsItem.getWorks());
		tvMean.setText(detailsItem.getMean() == null ? "Data is updating..."
				: detailsItem.getMean());

		// Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
		//
		// Session session = Session.getActiveSession();
		// if (session == null) {
		// if (savedInstanceState != null) {
		// session = Session.restoreSession(this, null, callback,
		// savedInstanceState);
		// }
		// if (session == null) {
		// session = new Session(this);
		// }
		// Session.setActiveSession(session);
		// if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
		// session.openForRead(new Session.OpenRequest(this).setCallback(
		// callback).setLoginBehavior(
		// SessionLoginBehavior.SUPPRESS_SSO));
		// }
		// }
	}

	public void buttonClick(View v) {
		switch (v.getId()) {
		case R.id.btnShare:
			shareVerb();
			break;

		default:
			break;
		}
	}

	Session session;

	private void shareVerb() {
		session = Session.getActiveSession();
		if (!session.isOpened()) {
			logIn();
		} else {
			getProfile(session);
		}
	}

	private void getProfile(Session session) {

		Bundle bundle = new Bundle();
		bundle.putString("fields", "name,picture.height(150).width(150)");
		final Request request = new Request(session, "/me", bundle,
				HttpMethod.GET, new Request.Callback() {

					@Override
					public void onCompleted(Response response) {
						GraphObject graphObject = response.getGraphObject();
						if (graphObject != null) {
							JSONObject jsonUser = graphObject
									.getInnerJSONObject();
							try {
								startPoss(jsonUser.getString("name"), jsonUser
										.getJSONObject("picture")
										.getJSONObject("data").getString("url"));

							} catch (JSONException e) {
								Log.e("", e.toString());
								Toast.makeText(getApplication(), "Error !",
										Toast.LENGTH_SHORT).show();
								e.printStackTrace();
							}
						}
					}
				});
		Request.executeBatchAsync(request);
	}

	Intent intent;
	Bundle bundle;

	private void startPoss(String name, String imageLink) {
		if (name == null || imageLink == null) {
			Toast.makeText(getApplication(), "Error !", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		intent = new Intent(getApplication(), NIPShowProfiles.class);
		bundle = new Bundle();
		bundle.putString(NAME_KEY, name);
		bundle.putString(IMAGE_LINK_KEY, imageLink);
		intent.putExtras(bundle);
		startActivityForResult(intent, REQUEST_CODE);
	}

	private void logIn() {
		session = Session.getActiveSession();
		if (!session.isOpened() && !session.isClosed()) {
			session.openForRead(new OpenRequest(this).setLoginBehavior(
					SessionLoginBehavior.SUPPRESS_SSO).setCallback(callback));
		} else {
			Session.openActiveSession(this, true, callback);
		}
	}

	private void logOut() {
		if (!Session.getActiveSession().isClosed()) {
			Session.getActiveSession().closeAndClearTokenInformation();
		}
	}

}
